<template>
  <!-- 账户管理 -->
  <div class="account-container">
    <PageCard title="单位信息维护">
      <el-form
        :model="ruleForm"
        size="small"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm w960"
      >
        <el-form-item
          label="单位名称"
          prop="name"
        >
          <el-input
            v-model="ruleForm.name"
            placeholder="请输入单位名称"
          ></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              label="简称"
              prop="shortName"
            >
              <el-input
                v-model="ruleForm.shortName"
                placeholder="请输入单位简称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="医疗机构编码"
              prop="code"
            >
              <el-input
                v-model="ruleForm.code"
                placeholder="请输入医疗机构编码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="医疗机构编号"
              prop="num"
            >
              <el-input
                v-model="ruleForm.num"
                disabled
                placeholder="系统自动生成"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="企业信用代码"
              prop="creditCode"
            >
              <el-input
                v-model="ruleForm.creditCode"
                placeholder="请输入企业信用代码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="省市区"
              prop="addressCode"
            >
              <tree-select
                :data="treeData"
                class="w100p"
                :defaultProps="defaultProps"
                :nodeKey="nodeKey"
                ref="treeselect"
                :checkedKeys="defaultCheckedKeys"
                @popoverHide="popoverHide"
              ></tree-select>
              <!-- <el-cascader
              class="w100p"
              v-model="ruleForm.addressCode"
              clearable
              :props="props"
              placeholder="请选择省市区"
              @change="handleLocationsChange"
            ></el-cascader> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="详细地址"
              prop="address"
            >
              <el-input
                v-model="ruleForm.address"
                placeholder="请输入详细地址"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="坐标位置"
              prop="address"
            >
              <div class="w100p s-d-inline-block">
                <span class="mr10">X</span>
                <el-input
                  readonly
                  class="w146"
                  v-model="ruleForm.longitude"
                  placeholder="请输入经度"
                ></el-input>
                <span class="ml20 mr10">Y</span>
                <el-input
                  readonly
                  class="w146"
                  v-model="ruleForm.latitude"
                  placeholder="请输入纬度"
                ></el-input>
                <el-button
                  @click="handleInnerVisible"
                  type="text"
                ><i class="el-icon-location-outline mr6 ml12"></i> 地图定位</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="handleSave">保 存</el-button>
        </el-form-item>
      </el-form>
      <el-dialog
        width="560px"
        title="坐标位置"
        append-to-body
        :visible.sync="innerVisible"
      >
        <BMap
          class="h390"
          ref="bmap"
        ></BMap>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            type="primary"
            @click="handleSaveBmap()"
            size="small"
          ><i class="el-icon-circle-check ml0 mr10 el-icon--right"></i> 确 定</el-button>
          <el-button
            size="small"
            @click="innerVisible = false"
          ><i class="el-icon-circle-close ml0 mr10 el-icon--right"></i> 取 消</el-button>
        </div>
      </el-dialog>
    </PageCard>

  </div>
</template>

<script>
import PageTable from "@/components/PageTable";
import PageCard from "@/components/PageCard";
import { hospitalBaseSave, hospitalBaseDetails } from "@/api/hospital.js";
import { settings } from "nprogress";
import * as areaApi from "@/api/area";
import { getUserInfo } from "@/utils/auth";
import TreeSelect from "@/components/TreeSelect";
import AMap from "@/components/AMap/AMap.vue";
import BMap from "@/components/BMap/index.vue";
export default {
  name: "Users",
  components: {
    PageTable: PageTable,
    PageCard: PageCard,
    AMap: AMap,
    BMap: BMap,
    TreeSelect: TreeSelect,
  },
  data() {
    const validateName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入单位名称"));
      } else if (
        value &&
        !/^[A-Za-z0-9]{1,100}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,50}$/.test(value)
      ) {
        callback(new Error("单位名称不超过100个英文字符或50个汉字"));
      } else {
        callback();
      }
    };
    const validateUserPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入管理员电话"));
      } else if (value && !/^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) {
        callback(new Error("电话有误，请重填"));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      {
        if (!value) {
          callback(new Error("请输入医疗机构编码"));
        } else if (value.length > 22) {
          callback(new Error("医疗机构编码长度小于22位"));
        } else {
          callback();
        }
      }
    };
    const validateCreditCode = (rule, value, callback) => {
      {
        if (!value) {
          callback(new Error("请输入企业信用代码"));
        } else if (value.length > 22) {
          callback(new Error("企业信用代码长度小于22位"));
        } else {
          callback();
        }
      }
    };
    const validateShortName = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入简称"));
      } else if (
        value &&
        !/^[A-Za-z0-9]{1,50}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,25}$/.test(value)
      ) {
        callback(new Error("简称不超过50个英文字符或25个汉字"));
      } else {
        callback();
      }
    };
    const validateAddress = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入详细地址"));
      } else if (value && !/^[A-Za-z0-9]{1,100}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,50}$/.test(value)) {
        callback(new Error("详细地址不超过100个英文字符或者50个汉字"));
      } else {
        callback();
      }
    };
    return {
      innerVisible: false,
      ruleForm: {
        address: "", //详细地址
        shortName: "", //简称
        adminMobile: "", //管理员电话
        adminName: "", //管理员名称
        cityCode: "", //市编码
        code: "", //医院编码
        creditCode: "", //信用代码
        id: "",
        adminId: "",
        addressCode: [],
        isFreeze: 1,
        name: "", //医院名称
        provinceCode: "", //省编码
        regionCode: "", //区编码
        townCode: "", //镇编码
        latitude: "",
        longitude: "",
      },
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name",
        isLeaf: false,
      },
      nodeKey: "code",
      defaultCheckedKeys: [],
      rules: {
        //form表单非空校验
        name: [
          {
            required: true,
            validator: validateName,
            trigger: "blur",
          },
        ],
        shortName: [
          {
            required: true,
            validator: validateShortName,
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            validator: validateCode,
            trigger: "blur",
          },
        ],
        creditCode: [
          {
            required: true,
            validator: validateCreditCode,
            trigger: "blur",
          },
        ],
        addressCode: [
          {
            required: true,
            message: "请选择省市区",
            trigger: "change",
          },
        ],
        address: [
          {
            required: true,
            validator:validateAddress,
            trigger: "blur",
          },
        ],
        adminName: [
          {
            required: true,
            message: "请输入管理员",
            trigger: "blur",
          },
        ],
        adminMobile: [
          {
            required: true,
            validator: validateUserPhone,
            trigger: "blur",
          },
        ],
        longitude: [
          {
            required: true,
            message: "请选择经纬度",
            trigger: "blur",
          },
        ], //经纬度
      },
      props: {
        children: "children",
        lazy: true,
        async lazyLoad(node, resolve) {
          const { level } = node;
          if (level == 0) {
            //省
            const { data } = await areaApi.getProvinceList();
            var nodes = data.map((item) => {
              return {
                value: item.code,
                label: item.name,
                leaf: false,
              };
            });
            resolve(nodes);
          } else if (level == 1) {
            const { data } = await areaApi.getCityList({
              provinceCode: node.data.value,
            }); //获取市接口
            var nodes = data.map((item) => {
              return {
                value: item.code,
                label: item.name,
                leaf: false,
              };
            });
            resolve(nodes);
          } else if (level == 2) {
            const { data } = await areaApi.getRegionList({
              cityCode: node.data.value,
            }); //获取市接口
            var nodes = data.map((item) => {
              return {
                value: item.code,
                label: item.name,
                leaf: false,
              };
            });
            resolve(nodes);
          } else if (level == 3) {
            const { data } = await areaApi.getTownList({
              regionCode: node.data.value,
            }); //获取市接口
            var nodes = data.map((item) => {
              return {
                value: item.code,
                label: item.name,
                leaf: true,
              };
            });
            resolve(nodes);
          }
        },
      },
    };
  },
  mounted() {
    this.handleGetDetails(); //获取机构详情
  },
  methods: {
    //获取地图数据
    handleSaveBmap(row) {
      let bMapForm = this.$refs.bmap.form;
      this.ruleForm.longitude = bMapForm.longitude;
      this.ruleForm.latitude = bMapForm.latitude;
      this.ruleForm.address = bMapForm.address;
      this.innerVisible = false;
    },
    //打开地图
    handleInnerVisible() {
      this.innerVisible = true;
      let _this = this;
      this.$nextTick(() => {
        if (_this.title == "新增医院机构") {
          // _this.$refs.bmap.handleInit({});
        } else {
          _this.$refs.bmap.handleInit(_this.ruleForm);
        }
      });
    },
    //获取医疗机构详情
    handleGetDetails() {
      let _this = this;
      let hospitalBaseId = getUserInfo()
        ? JSON.parse(getUserInfo()).hospitalBaseId
        : {};
      hospitalBaseDetails(hospitalBaseId).then(async (res) => {
        if (res && res.success) {
          this.$nextTick(async () => {
            this.ruleForm.addressCode = [];
            let ruleForm = res.data;
            _this.treeData = [];
            const { data } = await areaApi.getProvinceList();
            _this.treeData = data.map((item) => {
              item.children = [];
              return item;
            });
            this.defaultCheckedKeys = [
              res.data.townCode,
              res.data.regionCode,
              res.data.cityCode,
              res.data.provinceCode,
            ];
            this.$refs.treeselect.handleInit(this.treeData);

            ruleForm.addressCode = [
              res.data.provinceCode,
              res.data.cityCode,
              res.data.regionCode,
              res.data.townCode,
            ];
            this.ruleForm = JSON.parse(JSON.stringify(ruleForm));
            // this.$refs.bmap.handleInit(_this.ruleForm);
          });
        }
      });
    },
    //获取省市区数据
    handleLocationsChange(val) {
      this.ruleForm.addressCode = JSON.parse(JSON.stringify(val));
      this.ruleForm = Object.assign({}, this.ruleForm);
    },
    popoverHide(checkedIds, checkedData) {
      this.ruleForm.addressCode = [
        checkedData.provinceCode,
        checkedData.cityCode,
        checkedData.regionCode,
        checkedData.code,
      ];
      console.log(checkedIds);
      console.log(checkedData);
    },
    handleInputChange() {
      this.$refs.amap.searchByHand(this.ruleForm.address);
    },
    //获取经纬度
    handleGetLatLong(row) {
      this.ruleForm.latitude = row.lat;
      this.ruleForm.longitude = row.lng;
    },
    //保存
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // let bMapForm = this.$refs.bmap.form;
          let params = {
            address: this.ruleForm.address, //详细地址
            shortName: this.ruleForm.shortName, //简称
            adminMobile: this.ruleForm.adminMobile, //管理员电话
            adminName: this.ruleForm.adminName, //管理员名称
            cityCode: this.ruleForm.addressCode[1], //市编码
            code: this.ruleForm.code, //医院编码
            creditCode: this.ruleForm.creditCode,
            id: this.ruleForm.id,
            adminId: this.ruleForm.adminId,
            isFreeze: this.ruleForm.isFreeze,
            name: this.ruleForm.name, //医院名称
            provinceCode: this.ruleForm.addressCode[0], //省编码
            regionCode: this.ruleForm.addressCode[2], //区编码
            townCode: this.ruleForm.addressCode[3], //镇编码
            longitude: this.ruleForm.longitude,
            latitude: this.ruleForm.latitude,
          };
          hospitalBaseSave(params)
            .then((res) => {
              if (res && res.success) {
                this.loading = false;
                this.$message.success({
                  message: "保存成功",
                });
              } else {
                this.loading = false;
              }
            })
            .catch((e) => {
              this.loading = false;
            });
        } else {
          this.loading = false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.account-container {
  .btns {
    text-align: right;
  }
}
.demo-ruleForm {
  margin: 0 auto;
}
</style>
